package cn.g31010.sip.component
{
	import flash.events.Event;
	import flash.events.IOErrorEvent;
	import flash.media.Sound;
	import flash.media.SoundChannel;
	import flash.media.SoundMixer;
	import flash.media.SoundTransform;
	import flash.net.URLRequest;
	
	import mx.controls.Alert;
	import mx.managers.CursorManager;
	
	public class Sounder
	{
		private var sound:Sound;
		private var sc:SoundChannel;
		private var st:SoundTransform;
		private var playcount:int=1;
		[Bindable]
		public var vol:Number=0.5;
		private var position:Number;
		private static var sounder:Sounder;
		
		public function Sounder(){
			if(sounder!=null)
				throw new Error( "Only one Sounder instance should be instantiated" );	
			
		}
		
		public static function getInstance():Sounder{
			if(sounder==null){
				sounder= new Sounder();
			}
			return sounder;
		}
		
		public function getSoundTransform():SoundTransform{
			return st;
		}
		
		public function volume(v:Number):void{
			vol=v;
			if(st!=null){
				st.volume=vol;
				sc.soundTransform=st;
			}
		}
		
		public function pause():void{
			if(sc!=null){
				sc.stop();
				position=sc.position;
			}
		}
		
		public function resume():void{
			sc=sound.play(position,playcount);
    		st=sc.soundTransform;
    		st.volume=vol;
		}
		
		public function stop():void{
			SoundMixer.stopAll();
		}
		
		public function play(url:String,count:int=1):void{
			stop();
			playcount=count;
			sound=new Sound();
			sound.addEventListener(Event.COMPLETE,onComplete);
			sound.addEventListener(IOErrorEvent.IO_ERROR,onError);
			CursorManager.setBusyCursor();
			sound.load(new URLRequest(url));
		}
		private function onComplete(e:Event):void{
			CursorManager.removeAllCursors();
    		sc=sound.play(0,playcount);
    		st=sc.soundTransform;
    		st.volume=vol;
    		
		}
		
		private function onError(e:IOErrorEvent):void{
			CursorManager.removeAllCursors();
			Alert.show("无法播放");
		}		
		
	}
}